﻿using ERP.Inventory.Api.Read.Application.Command.库存管理;
using ERP.Inventory.Api.Read.DTO;
using ERP.Inventory.Domain.库存管理;
using ERP.Inventory.Errorcode;
using ERP.Inventory.Infastructure.Interface;
using MediatR;
using System.Diagnostics;

namespace ERP.Inventory.Api.Read.Application.Handler.库存管理
{
    public class GetCheckShopHandler : IRequestHandler<GetCheckShopCommand, ApiPaging<ShopandcheckDTO>>
    {
        private readonly IBaseRepository<ShopModel> shopRepo;
        private readonly IBaseRepository<CheckandShopModel> checkshopRepo;

        public GetCheckShopHandler(IBaseRepository<ShopModel> shopRepo, IBaseRepository<CheckandShopModel> checkshopRepo)
        {
            this.shopRepo = shopRepo;
            this.checkshopRepo = checkshopRepo;
        }
        public async Task<ApiPaging<ShopandcheckDTO>> Handle(GetCheckShopCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiPaging<ShopandcheckDTO>();
            var checkshop = checkshopRepo.GetAll().Where(x => x.InvenId == request.InvenId).Select(x => request.ShopId);
            var l = from a in shopRepo.GetAll()
                    join b in checkshopRepo.GetAll()
                    on a.Id equals b.ShopId
                    select new ShopandcheckDTO
                    {
                        Id = a.Id,
                        ShopName = a.ShopName,
                        ShopCode = a.ShopCode,
                        ShopGui = a.ShopGui,
                        ShopUnit = a.ShopUnit,
                        SystemNum = a.SystemNum,
                        ActualNum = a.ActualNum,
                        DifferentCount = a.DifferentCount,
                        InvenId = b.InvenId,
                        ShopId = b.ShopId,
                    };
            var totalcount = l.Count();
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.PageSize);
            l = l.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            res.totalcount = totalcount;
            res.totalpage = totalpage;
            res.Message = "显示成功";
            res.Data = l.ToList();
            res.Code = ApiEnum.Ok;
            return await Task.FromResult(res);
        }
    }
}
